package com.lam.dormitory.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lam.dormitory.entity.Role;
import com.lam.dormitory.entity.RolePermission;
import com.lam.dormitory.mapper.RoleMapper;
import com.lam.dormitory.mapper.RolePermissionMapper;
import com.lam.dormitory.service.IRoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lam.dormitory.util.ResponseTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author lam
 * @since 2019-12-20
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements IRoleService {
    @Autowired
    private RolePermissionMapper rolePermissionMapper;
    @Override
    public List<Role> selectRoleByUserId(Long userId) {
        return this.baseMapper.selectRoleByUserId(userId);
    }

    @Override
    public Role selectRoleByName(String name) {
        QueryWrapper<Role> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(Role::getName,name);
        return this.baseMapper.selectOne(wrapper);
    }

    @Override
    public List<Role> selectByRole(Role role) {
        return this.baseMapper.selectByRole(role);
    }

    @Override
    public ResponseTemplate addAssignPermission(Long roleId, List<Long> permissionIds) {
        try {
            RolePermission rolePermission = new RolePermission();
            rolePermission.setRoleId(roleId);
            QueryWrapper<RolePermission> wrapper = new QueryWrapper<>(rolePermission);
            rolePermissionMapper.delete(wrapper);
            for (Long permissionId : permissionIds) {
                rolePermission.setPermissionId(permissionId);
                rolePermissionMapper.insert(rolePermission);
            }
            return new ResponseTemplate(200,"分配权限成功");
        } catch (Exception e) {
            return new ResponseTemplate(500,"分配权限失败");

        }
    }

}
